<template>
    <div id="AddArticlePage" class="px-5 py-5">
        <span class="text-3xl font-bold text-gray-900">
            {{ route.query?.id ? '修改文章' : '新建文章' }}
        </span>

        <el-form
                :model="articleForm"
                :rules="rules"
                label-width="auto"
                status-icon
                ref="formRef"
                class="my-4"
        >
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="articleForm.title"/>
            </el-form-item>
            <el-form-item label="文章分类" prop="category">
                <el-select
                        v-model="articleForm.category"
                        placeholder="请选择分类">
                    <el-option
                            v-for="item in categoryList"
                            :key="item"
                            :label="item"
                            :value="item"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="文章分类" prop="tags">
                <el-select
                        multiple
                        filterable
                        allow-create
                        v-model="articleForm.tags"
                        placeholder="请选择分类">
                    <el-option
                            v-for="item in tagList"
                            :key="item"
                            :label="item"
                            :value="item"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="封面预览">
                <el-image style="width: 80px;height: 80px;" :src="articleForm.coverUrl"/>
            </el-form-item>
            <el-form-item label="文章封面">
                <el-upload
                        class="upload-demo"
                        action="http://localhost:8080/api/files/upload"
                        :on-success="handleFileSuccess"
                        :before-upload="beforeAvatarUpload"
                        :limit="1"
                        :show-file-list="false"
                >
                    <el-button type="primary">上传封面</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item prop="content" label="文章内容">
                <div class="w-full">
                    <MdEditor
                            toolbarsExclude="['link', 'mermaid', 'katex', 'github']"
                            v-model="articleForm.content"
                            @onSave="codeSave"
                            @onUploadImg="onUploadImg"/>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import {useRoute, useRouter} from "vue-router";
import {onMounted, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import myAxios from "@/axios/axios.js";
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';


const formRef = ref();
const text = ref('Hello Editor!');
const router = useRouter()
const route = useRoute()
const article = ref({})
const articleForm = reactive({})
const tagList = ref([])
const categoryList = ref([])
const codeSave = (v) => {
    ElMessage.info('已保存')
    localStorage.setItem('codeSave', v)
}
const onUploadImg = async (files, callback) => {
    const res = await Promise.all(
        files.map((file) => {
            return new Promise((rev, rej) => {
                const form = new FormData();
                form.append('file', file);

                myAxios
                    .post('/files/wang/upload', form, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                        },
                    })
                    .then((res) => rev(res))
                    .catch((error) => rej(error));
            });
        })
    );

    callback(res.map((item) => item.data.url));
};

const handleFileSuccess = (res) => {
    if (res.data) {
        article.coverUrl = res.data;
        ElMessage.success('文章封面上传成功');
    } else {
        ElMessage.error('文章封面上传失败');
    }
};
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/png') {
        ElMessage.error('图片格式需为 png !');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过 2MB !');
        return false;
    }
    return true;
};


// 表单验证规则
const rules = reactive({
    title: [
        {required: true, message: '请输入文章标题', trigger: 'blur'}
    ],
    content: [
        {required: true, message: '请输入文章内容', trigger: 'blur'}
    ]
});
// 获取老数据
const getOldArticle = async () => {
    // 获取数据
    const id = route.query?.id
    if (id) {
        const res = await myAxios.get('/article/get/' + id,)
        if (res.code === 0 && res.data) {
            const data = res.data
            articleForm.content = data.content
            articleForm.coverUrl = data.coverUrl
            articleForm.id = data.id
            articleForm.title = data.title
            articleForm.description = data.description
            articleForm.category = data.category
            articleForm.tags = data.tags
        }
    }
}


// 提交表单
const onSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            return;
        }
        if (articleForm.id) {
            updateNotice();
        } else {
            addNotice();
        }
    });
};

// 新增文章
const addNotice = async () => {
    try {
        const res = await myAxios.post("/article/add", articleForm);
        if (res.code === 0) {
            ElMessage.success("文章创建成功");
            await router.back()
        } else {
            ElMessage.error("文章创建失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("文章创建出错:", error);
    }
};

// 更新文章
const updateNotice = async () => {
    try {
        const res = await myAxios.post("/article/update", articleForm);
        if (res.code === 0) {
            ElMessage.success("文章更新成功");

            await router.back()
        } else {
            ElMessage.error("文章更新失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("文章更新出错:", error);
    }
};

const getCategoryList = async () => {
    try {
        const res = await myAxios.get("/article/tag_category");
        if (res.code === 0 && res.data) {
            console.log(res.data.categoryList)
            console.log(res.data.tagList)
            tagList.value = res.data.tagList;
            categoryList.value = res.data.categoryList;
        } else {
            ElMessage.error("数据加载失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("数据加载出错:", error);
    }
};
onMounted(() => {
    getOldArticle()
    getCategoryList()
})
</script>

<style scoped>
#AddArticlePage {
}

</style>
